# -- coding: utf-8 --
# @time : 2023/6/1
# @author : 周梦泽
# @file : title_creator.py
# @software: pycharm
# 用于店铺宝贝标题
# 改自：
# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/4/17 14:16
解析表格数据为商品标题
"""
import time
from dataclasses import dataclass

from DrissionPage import WebPage
from DrissionPage.action_chains import ActionChains
from DrissionPage.commons.keys import Keys

from autoTask.taobao.taobao_login import Login
from common.logger.log import log_
from common.utils import web_page_util
from common.utils.web_page_util import ActionChain, MockTap, Input, MockMove


@dataclass
class ParseExcelToTitle:
    """
    解析 Excel 表格生成并设置商品标题。
    Attributes:
        product_id(int): 商品id
        new_title(str): 新商品标题
        tb_username(str): 淘宝账号
        tb_password(str): 淘宝密码
        page(WebPage): 页面对象
        is_test_execute(bool): 是否为测试执行
    """

    product: dict = None
    tb_username: str = ''
    tb_password: str = ''
    page: WebPage = None
    is_test_execute: bool = False

    def __call__(self, param: dict = None):
        """
        :param param: 重新初始化的变量
        :return:
        """

        if param:
            self.by_param_init(param)

        # 跳转至首页
        self.go_to_index_view()
        for product in self.product:

            product_id = product.get('productId')
            new_title = product.get('newTitle')
            log_.info(f"设置目标商品标题  商品id: {product_id}, 新标题: {new_title}")
            # 设置页面条件
            self.set_view_condition(product_id)
            # 设置出标题
            self.set_title_action(new_title, product_id)
        log_.info("生成并设置商品标题完毕")

    def __post_init__(self):
        self.cache_links = {
            '首页': 'https://myseller.taobao.com/home.htm'
        }

    def by_param_init(self, param: dict = None):
        """
        根据传入的字典初始化对象
        :param param: 参数
        :return:
        """
        self.tb_username = param.get('account')
        self.tb_password = param.get('password')
        self.is_test_execute = param.get('isTestExecute')
        self.product = param.get('product')

    def set_title_action(self, new_title, product_id):
        """
        设置标题动作
        :param new_title 新标题
        :param product_id 目标商品id
        :return:
        """
        total_text = self.page(".next-pagination-total").text
        if total_text != '共1件商品':
            log_.warning(f"没有精确的搜索到目标商品 商品ID: {product_id} text : {total_text}")
            return
        title_el = self.page("tag:a@@class=title-link")
        MockMove(title_el, before_delay=(1, 2), after_delay=(2, 3),
                 msg="移动鼠标至商品标题")()
        MockTap(title_el.next(), after_delay=(1, 3), msg="打开标题编辑窗", reduce_scope=(5, 5))()
        Input(self.page(".ipt-content")("tag:input"), msg="输入新标题", vals=new_title, after_delay=(2, 3))()
        if not self.is_test_execute:
            MockTap(self.page(".next-dialog-footer next-align-right")("tx:提交"), after_delay=(2, 3))()
        else:
            MockTap(self.page(".next-dialog-footer next-align-right")("tx:取消"), after_delay=(2, 3))()

    def go_to_index_view(self):
        """
        跳转到任务首页
        :return:
        """
        index_url = self.cache_links.get('首页')
        # 登录
        if self.page is None:
            self.page, _ = Login(account=self.tb_username, password=self.tb_password).execute()
        if not self.page.url.startswith(index_url):
            self.page.get(index_url)
            self.page.wait.load_start(timeout=10)
        self.page.refresh()
        self.page.wait.load_start(30)
        # //div/a[@data-index='1']/span[contains(@class,'FirstClassMenu')]  商品xpath
        ActionChain(self.page)([
            MockTap("tag=span@@text()=商品", before_delay=(2, 3), after_delay=(4, 5), reduce_scope=(1, 10),
                    msg="点击商品标签页失败"),
            MockTap("tag=a@@text()=我的宝贝", before_delay=(2, 3), after_delay=(2, 3),
                    msg="点击我的宝贝标签页失败")
        ])

    def set_view_condition(self, product_id):
        """
        设置页面相关条件
        :param product_id 目标商品id
        :return:
        """
        input_e = self.page("x://input[@id='queryItemId']")
        Input(input_e, "输入商品ID", vals=product_id,
              before_delay=(1, 3), after_delay=(1, 3))()
        ActionChains(self.page).key_down(Keys.ENTER)
        time.sleep(3)
        web_page_util.wait_ele_disappear(self.page, ".next-loading-tip", 30)
